#!/bin/bash

# 注意看脚本里各需要文件的路径，主要是u-boot-sunxi-with-spl.bin、uImage、boot.scr、script.bin、rootfs.tar.gz

set -e
loopx=loop21 # 指定挂载设备，可以根据自己的开发环境修改，比如 loop25

dd if=/dev/zero of=lichee_zero.img bs=1M count=100

parted lichee_zero.img --script -- mklabel msdos #制作一个msdos分区
parted lichee_zero.img --script -- mkpart primary fat16 2048s 67583s #分区1
parted lichee_zero.img --script -- mkpart primary ext4 67584s -1 #分区2

sudo losetup /dev/$loopx lichee_zero.img
sudo kpartx -av /dev/$loopx

sudo mkfs.msdos /dev/mapper/${loopx}p1
sudo mkfs.ext4 /dev/mapper/${loopx}p2

sudo dd if=u-boot/u-boot-sunxi-with-spl.bin of=/dev/$loopx bs=1024 seek=8
sync

mkdir /tmp/p1
sudo mount /dev/mapper/${loopx}p1 /tmp/p1/
sudo cp lichee/linux-3.4/arch/arm/boot/uImage /tmp/p1/
sudo cp u-boot/boot.scr /tmp/p1/
sudo cp u-boot/script.bin /tmp/p1/
sudo umount /tmp/p1
rm /tmp/p1 -rf

mkdir /tmp/p2
sudo tune2fs -O ^metadata_csum /dev/mapper/${loopx}p2
sudo e2fsck -f -a -v /dev/mapper/${loopx}p2
sudo tune2fs -O ^metadata_csum /dev/mapper/${loopx}p2
sudo mount -t ext4 /dev/mapper/${loopx}p2 /tmp/p2/
sudo tar -xzvf buildroot-2017.08/output/images/rootfs.tar.gz -C /tmp/p2/
sudo umount /tmp/p2
rm /tmp/p2 -rf

sudo kpartx -d lichee_zero.img